package net.esj.basic.plugins.struts2.interceptor;

import java.lang.reflect.Method;

import javax.inject.Inject;

import net.esj.basic.core.engine.factory.bean.BeanFactory;
import net.esj.basic.plugins.struts2.Immit;
import net.esj.basic.plugins.struts2.aware.OsgiAware;
import net.esj.basic.utils.Validators;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class OsgiInjectInterceptor extends AbstractInterceptor {

	private BeanFactory beanFactory;
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Object o = invocation.getAction();
		if(o instanceof OsgiAware){
			OsgiAware aware = (OsgiAware) o;
			for(Method method: invocation.getAction().getClass().getDeclaredMethods()){
				if(method.isAnnotationPresent(Immit.class)||
						method.isAnnotationPresent(Inject.class)){
					String beanname = resolveBeanName(method.getName());//先按名字匹配，如果找不到再按类型匹配
					if(!Validators.isEmpty(beanname)){
						Object bean = beanFactory.getBean(beanname);
						if(bean!=null){
							method.invoke(invocation.getAction(), bean);
							return invocation.invoke();
						}
					}
					Class clazzintef = method.getParameterTypes()[0];
					Object bean = beanFactory.getBean(clazzintef);
					if(bean!=null){
						method.invoke(invocation.getAction(), bean);
					}
				}
			}
		}
		return invocation.invoke();
	}
	
	private String resolveBeanName(String methodName){
		String name = "";
		if(methodName.startsWith("set")){
			name = methodName.substring(3);
		}
		if(name.length() > 0 &&
	                        Character.isUpperCase(name.charAt(0))){
			if (name.length() == 1) {
				name = name.toLowerCase();
            } else if (!Character.isUpperCase(name.charAt(1))) {
            	name = name.substring(0, 1).toLowerCase() +
            	name.substring(1);
            }
		}
		return name;
	}

	@Inject
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

}
